package com.example.demo.design.demo21_singleton;

/**
 * Created by 蔡超 on 2018/10/8.
 */
public class Singleton {
    private static Singleton singleton;

    private Singleton(){

    }

    public static Singleton getInstance() throws InterruptedException {
        if(singleton == null){
            synchronized (Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    public static Singleton getInstance2() throws InterruptedException {
        if(singleton == null){
            Thread.sleep((long) (Math.random() * 2000));
            singleton = new Singleton();
        }
        return singleton;
    }

    public static Singleton getInstance3() throws InterruptedException {
        return new Singleton();
    }

    public static void main(String[] args) throws InterruptedException {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2);

        Singleton singleton2_1 = Singleton.getInstance2();
        Singleton singleton2_2 = Singleton.getInstance2();
        System.out.println(singleton2_1 == singleton2_2);


        Singleton singleton3_1 = Singleton.getInstance3();
        Singleton singleton3_2 = Singleton.getInstance3();
        System.out.println(singleton3_1 == singleton3_2);

        for (int i = 0; i < 20; i++) {
            Thread thread = new ThreadTest();
            thread.start();
        }

    }

}
